﻿using System;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Globalization;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using SimpleScrum.Areas.Admin.Models;
using SimpleScrum.Areas.Scrum.Models;
using SimpleScrum.Core.Entities;
using SimpleScrum.Utils;
using WebMatrix.WebData;

namespace SimpleScrum.Areas.Admin.Controllers
{
    [Authorize(Roles = "admin")]
    public class ControlPanelController : Controller
    {
        public UsersModel ObjUsers;
        public ControlPanelController()
        {
            ObjUsers = new UsersModel();
        }
        // GET: /Admin/

        //member

        //#region Membership Controller
        ////#region ctors

        ////Membership membershipServic = new Membership();
        ////private readonly Roles roleService = new Roles();

        ////public MembershipController()
        ////{
        ////    this.roleService = new RoleService(Roles.Provider);
        ////    this.Membership = new Membership(Membership.Provider);
        ////}

        ////#endregion

        //#region Membership Method
        //public virtual ActionResult Membership(string filterby, string searchterm)
        //{
        //    ManageUsersViewModel viewModel = new ManageUsersViewModel();
        //    viewModel.Users = null;
        //    viewModel.FilterBy = filterby;
        //    viewModel.SearchTerm = searchterm;

        //    int totalRecords;
        //    int page = Convert.ToInt32(Request["page"]);
        //    int pageSize = Convert.ToInt32(Request["pagesize"]);
        //    if (pageSize == 0)
        //        pageSize = 25;

        //    viewModel.PageSize = pageSize;

        //    if (!string.IsNullOrEmpty(filterby))
        //    {
        //        if (filterby == "all")
        //        {
        //            viewModel.PaginatedUserList = Membership.GetAllUsers(page, pageSize, out totalRecords).ToPaginatedList(page, pageSize, totalRecords, searchterm, filterby);
        //        }
        //        else if (!string.IsNullOrEmpty(searchterm))
        //        {
        //            string query = searchterm + "%";
        //            if (filterby == "email")
        //            {
        //                viewModel.PaginatedUserList = Membership.FindUsersByEmail(query, page, pageSize, out totalRecords).ToPaginatedList(page, pageSize, totalRecords, searchterm, filterby);
        //            }
        //            else if (filterby == "email")
        //            {
        //                viewModel.PaginatedUserList = Membership.FindUsersByName(query, page, pageSize, out totalRecords).ToPaginatedList(page, pageSize, totalRecords, searchterm, filterby);
        //            }
        //        }
        //    }

        //    return View(viewModel);
        //}
        //#endregion

        //#region Create User Methods

        //public virtual ActionResult MembershipCreateUser()
        //{
        //    var model = new RegisterViewModel()
        //    {
        //        RequireSecretQuestionAndAnswer = Membership.RequiresQuestionAndAnswer
        //    };
        //    return View(model);
        //}

        ///// <summary>
        ///// This method redirects to the GrantRolesToUser method.
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public virtual ActionResult MembershipCreateUser(RegisterViewModel model)
        //{
        //    MembershipUser user;
        //    MembershipCreateStatus status;
        //    user = MembershipUser.CreateUser(model.Email, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, model.Approve, out status);

        //    return routeHelpers.Actions.GrantRolesToUser(user.email);
        //}

        ///// <summary>
        ///// An Ajax method to check if a email is unique.
        ///// </summary>
        ///// <param name="email"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public ActionResult CheckForUniqueUser(string email)
        //{
        //    MembershipUser user = MembershipUser.GetUser(email);
        //    JsonResponse response = new JsonResponse();
        //    response.Exists = (user == null) ? false : true;

        //    return Json(response, JsonRequestBehavior.AllowGet);
        //}

        //#endregion

        //#region Delete User Methods

        //[HttpPost]
        ////[MultiButtonFormSubmit(ActionName = "UpdateDeleteCancel", SubmitButton = "DeleteUser")]
        //public ActionResult DeleteUser(string email)
        //{
        //    if (string.IsNullOrEmpty(email))
        //    {
        //        throw new ArgumentNullException("email");
        //    }

        //    try
        //    {
        //        MembershipUser.DeleteUser(email);
        //        return RedirectToAction("Membership");
        //    }
        //    catch (Exception ex)
        //    {
        //        TempData["ErrorMessage"] = "There was an error deleting this user. - " + ex.Message;
        //    }

        //    return RedirectToAction("MembershipUpdate", new { email = email });
        //}


        //#endregion

        //#region View User Details Methods

        //[HttpGet]
        //public ActionResult MembershipUpdate(string email)
        //{
        //    MembershipUser user = Membership.GetUser(email);

        //    UserViewModel viewModel = new UserViewModel();
        //    viewModel.User = user;
        //    viewModel.RequiresSecretQuestionAndAnswer = Membership.RequiresQuestionAndAnswer;
        //    viewModel.Roles = Roles.GetRolesForUser(email);

        //    return View(viewModel);
        //}

        //[HttpPost]
        ////[ActionName("Update")]
        ////[MultiButtonFormSubmit(ActionName = "UpdateDeleteCancel", SubmitButton = "UpdateUser")]
        //public ActionResult UpdateUser(string email)
        //{
        //    if (string.IsNullOrEmpty(email))
        //    {
        //        throw new ArgumentNullException("email");
        //    }

        //    MembershipUser user = Membership.GetUser(email);

        //    try
        //    {
        //        user.Comment = Request["User.Comment"];
        //        user.Email = Request["User.Email"];

        //        Membership.UpdateUser(user);
        //        TempData["SuccessMessage"] = "The user was updated successfully!";

        //    }
        //    catch (Exception)
        //    {
        //        TempData["ErrorMessage"] = "There was an error updating this user.";
        //    }

        //    return RedirectToAction("MembershipUpdate", new { email = user.email });
        //}


        //#region Ajax methods for Updating the user

        //[HttpPost]
        //public ActionResult Unlock(string email)
        //{
        //    JsonResponse response = new JsonResponse();

        //    MembershipUser user = Membership.GetUser(email);

        //    try
        //    {
        //        user.UnlockUser();
        //        response.Success = true;
        //        response.Message = "User unlocked successfully!";
        //        response.Locked = false;
        //        response.LockedStatus = (response.Locked) ? "Locked" : "Unlocked";
        //    }
        //    catch (Exception)
        //    {
        //        response.Success = false;
        //        response.Message = "User unlocked failed.";
        //    }

        //    return Json(response);
        //}

        //[HttpPost]
        //public ActionResult ApproveDeny(string email)
        //{
        //    JsonResponse response = new JsonResponse();

        //    MembershipUser user = Membership.GetUser(email);

        //    try
        //    {
        //        user.IsApproved = !user.IsApproved;
        //        Membership.UpdateUser(user);

        //        string approvedMsg = (user.IsApproved) ? "Approved" : "Denied";

        //        response.Success = true;
        //        response.Message = "User " + approvedMsg + " successfully!";
        //        response.Approved = user.IsApproved;
        //        response.ApprovedStatus = (user.IsApproved) ? "Approved" : "Not approved";
        //    }
        //    catch (Exception)
        //    {
        //        response.Success = false;
        //        response.Message = "User unlocked failed.";
        //    }

        //    return Json(response);
        //}

        //#endregion

        //#endregion

        //#region Cancel User Methods

        //[HttpPost]
        ////[MultiButtonFormSubmit(ActionName = "UpdateDeleteCancel", SubmitButton = "UserCancel")]
        //public ActionResult Cancel()
        //{
        //    return RedirectToAction("Membership");
        //}

        //#endregion

        //#region Membership Grant Users with Roles Methods

        ///// <summary>
        ///// Return two lists:
        /////   1)  a list of Roles not granted to the user
        /////   2)  a list of Roles granted to the user
        ///// </summary>
        ///// <param name="email"></param>
        ///// <returns></returns>
        //public virtual ActionResult MembershipGrantRolesToUser(string email)
        //{
        //    if (string.IsNullOrEmpty(email))
        //    {
        //        return RedirectToAction("Membership");
        //    }

        //    GrantRolesToUserViewModel model = new GrantRolesToUserViewModel();
        //    model.UserName = email;
        //    model.AvailableRoles = (string.IsNullOrEmpty(email) ? new SelectList(Roles.GetAllRoles()) : new SelectList(Roles.AvailableRolesForUser(email)));
        //    model.GrantedRoles = (string.IsNullOrEmpty(email) ? new SelectList(new string[] { }) : new SelectList(Roles.GetRolesForUser(email)));

        //    return View(model);
        //}

        ///// <summary>
        ///// Grant the selected roles to the user.
        ///// </summary>
        ///// <param name="email"></param>
        ///// <param name="roleNames"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public virtual ActionResult MembershipGrantRolesToUser(string email, string roles)
        //{
        //    JsonResponse response = new JsonResponse();

        //    if (string.IsNullOrEmpty(email))
        //    {
        //        response.Success = false;
        //        response.Message = "The email is missing.";
        //        return Json(response);
        //    }

        //    string[] roleNames = roles.Substring(0, roles.Length - 1).Split(',');

        //    if (roleNames.Length == 0)
        //    {
        //        response.Success = false;
        //        response.Message = "No roles have been granted to the user.";
        //        return Json(response);
        //    }

        //    try
        //    {
        //        Roles.AddUserToRoles(email, roleNames);

        //        response.Success = true;
        //        response.Message = "The Role(s) has been GRANTED successfully to " + email;
        //    }
        //    catch (Exception)
        //    {
        //        response.Success = false;
        //        response.Message = "There was a problem adding the user to the roles.";
        //    }

        //    return Json(response);
        //}

        ///// <summary>
        ///// Revoke the selected roles for the user.
        ///// </summary>
        ///// <param name="email"></param>
        ///// <param name="roleNames"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult RevokeRolesForUser(string email, string roles)
        //{
        //    JsonResponse response = new JsonResponse();

        //    if (string.IsNullOrEmpty(email))
        //    {
        //        response.Success = false;
        //        response.Message = "The email is missing.";
        //        return Json(response);
        //    }

        //    if (string.IsNullOrEmpty(roles))
        //    {
        //        response.Success = false;
        //        response.Message = "Roles is missing";
        //        return Json(response);
        //    }

        //    string[] roleNames = roles.Substring(0, roles.Length - 1).Split(',');

        //    if (roleNames.Length == 0)
        //    {
        //        response.Success = false;
        //        response.Message = "No roles are selected to be revoked.";
        //        return Json(response);
        //    }

        //    try
        //    {
        //        Roles.RemoveUserFromRoles(email, roleNames);

        //        response.Success = true;
        //        response.Message = "The Role(s) has been REVOKED successfully for " + email;
        //    }
        //    catch (Exception)
        //    {
        //        response.Success = false;
        //        response.Message = "There was a problem revoking roles for the user.";
        //    }

        //    return Json(response);
        //}

        //#endregion
        //#endregion


        //role

        //extra.......
        private readonly RolesModel model = new RolesModel();

        //
        // GET:

        public ActionResult Manage()
        {
            return RedirectToRoute("Account");
        }

        //
        // POST: /Account/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            if (HttpContext.Session != null) HttpContext.Session.Abandon();
            WebSecurity.Logout();
            Session.Remove("facebooktoken");

            return RedirectToRoute("Default", new {action = "Index", controller = "Home"});
        }

        public ActionResult Index()
        {
            Guid id = ObjUsers.GetUsersIdByEmail();
            Users user = ObjUsers.GetUsersById(id);
            Client.Instance.ClientId = id;
            Client.Instance.ClientName = user.FirstName + " " + user.LastName;
            var adminViewModel = new AdminViewModel();
            int totalRecords;
            //Membership.GetAllUsers(0, 20, out totalRecords);
            //adminViewModel.TotalUserCount = totalRecords.ToString(CultureInfo.InvariantCulture);
            //adminViewModel.TotalUsersOnlineCount = Membership.GetNumberOfUsersOnline().ToString(CultureInfo.InvariantCulture);
            adminViewModel.TotalRolesCount = Roles.GetAllRoles().Length.ToString(CultureInfo.InvariantCulture);

            return View(adminViewModel);
        }

        public ActionResult ShowRoles()
        {
            model.Roles = Roles.GetAllRoles();
            return View(model);
        }

        public ActionResult AccountManagement()
        {
            if (Roles.GetRolesForUser().Length > 0)
            {
                //Roles.RemoveUserFromRoles(model.Email, Roles.GetRolesForUser());
            }
            if (model.Roles != null && model.Roles.Length > 0)
            {
                Roles.AddUserToRoles(model.Email, model.Roles);
            }
            return View();
        }
        #region Role Controller
        public virtual ActionResult RoleView()
        {
            var manageRolesViewModel = new ManageRolesViewModel
                {
                    Roles = new SelectList(Roles.GetAllRoles()),
                    RoleList = Roles.GetAllRoles()
                };

            return View(manageRolesViewModel);
        }

        #region Create Roles Methods

        [HttpGet]
        public virtual ActionResult CreateRole()
        {
            return View(new RoleViewModel());
        }

        [HttpPost]
        public virtual ActionResult CreateRole(string roleName)
        {
            var response = new JsonResponse();

            if (string.IsNullOrEmpty(roleName))
            {
                response.Success = false;
                response.Message = "You must enter a role name.";
                response.CssClass = "red";

                return Json(response);
            }

            try
            {
                Roles.CreateRole(roleName);

                if (Request.IsAjaxRequest())
                {
                    response.Success = true;
                    response.Message = "Role created successfully!";
                    response.CssClass = "green";

                    return Json(response);
                }

                return RedirectToAction("RoleView");
            }
            catch (Exception ex)
            {
                if (Request.IsAjaxRequest())
                {
                    response.Success = false;
                    response.Message = ex.Message;
                    response.CssClass = "red";

                    return Json(response);
                }

                ModelState.AddModelError("", ex.Message);
            }

            return RedirectToAction("RoleView");
        }

        #endregion

        #region Delete Roles Methods

        /// <summary>
        ///     This is an Ajax method.
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual ActionResult DeleteRole(string roleName)
        {
            var response = new JsonResponse();

            if (string.IsNullOrEmpty(roleName))
            {
                response.Success = false;
                response.Message = "You must select a Role Name to delete.";
                response.CssClass = "red";

                return Json(response);
            }

            Roles.DeleteRole(roleName);

            response.Success = true;
            response.Message = roleName + " was deleted successfully!";
            response.CssClass = "green";

            return Json(response);
        }

        [HttpPost]
        public ActionResult DeleteRoles(string roles, bool throwOnPopulatedRole)
        {
            var response = new JsonResponse();
            response.Messages = new List<ResponseItem>();

            if (string.IsNullOrEmpty(roles))
            {
                response.Success = false;
                response.Message = "You must select at least one role.";
                return Json(response);
            }

            string[] roleNames = roles.Split(',');
            var sb = new StringBuilder();

            ResponseItem item = null;

            foreach (string role in roleNames)
            {
                if (!string.IsNullOrEmpty(role))
                {
                    try
                    {
                        Roles.DeleteRole(role, throwOnPopulatedRole);

                        item = new ResponseItem();
                        item.Success = true;
                        item.Message = "Deleted this role successfully - " + role;
                        item.CssClass = "green";
                        response.Messages.Add(item);

                        //sb.AppendLine("Deleted this role successfully - " + role + "<br />");
                    }
                    catch (ProviderException ex)
                    {
                        //sb.AppendLine(role + " - " + ex.Message + "<br />");

                        item = new ResponseItem();
                        item.Success = false;
                        item.Message = ex.Message;
                        item.CssClass = "yellow";
                        response.Messages.Add(item);
                    }
                }
            }

            response.Success = true;
            response.Message = sb.ToString();

            return Json(response);
        }

        #endregion

        #region Get Users In Role methods

        /// <summary>
        ///     This is an Ajax method that populates the
        ///     Roles drop down list.
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllRoles()
        {
            string[] list = Roles.GetAllRoles();

            var selectList = new List<SelectObject>();

            foreach (string item in list)
            {
                selectList.Add(new SelectObject {caption = item, value = item});
            }

            return Json(selectList, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult GetUsersInRole(string roleName)
        {
            string[] list = Roles.GetUsersInRole(roleName);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #endregion
    }
}